package cn.leedsoft.and.crimeintent.common;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.AsyncTaskLoader;

/**
 * Created by leeds on 2016/9/7 16:04.
 */
public abstract class SQLiteCursorLoader extends AsyncTaskLoader<Cursor> {
    private Cursor mCursor;

    public SQLiteCursorLoader(Context context) {
        super(context);
    }

    @Override
    public Cursor loadInBackground() {
        Cursor cursor = loadCursor();
        if(cursor != null) {
            cursor.getCount();//保证数据在发送给主线程之前已加载到内存中
        }
        return cursor;
    }

    protected abstract Cursor loadCursor();

    @Override
    public void deliverResult(Cursor data) {
        Cursor oldCursor = mCursor;
        mCursor = data;

        if (isStarted()) {//如果loader启动了（这表示数据可以发送了），超类版本的deliverResult(...)方法会被调用
            super.deliverResult(data);
        }

        if(oldCursor != null && oldCursor != data//现有cursor可能会被缓存或重新发送，因此在关闭旧的cursor前，必须确认新旧cursor并不相同
                && !oldCursor.isClosed()) {
            oldCursor.close();//旧的cursor不再需要，关闭以释放资源
        }
    }

    @Override
    protected void onStartLoading() {
        if(mCursor != null) {
            deliverResult(mCursor);
        }

        if(takeContentChanged() || mCursor == null) {
            forceLoad();
        }
    }

    @Override
    protected void onStopLoading() {
        cancelLoad();
    }

    @Override
    public void onCanceled(Cursor data) {
        if(data != null && !data.isClosed()) {
            data.close();//关闭cursor
        }
    }

    @Override
    protected void onReset() {
        onStopLoading();

        if(mCursor != null && !mCursor.isClosed()) {
            mCursor.close();//关闭cursor
        }
        mCursor = null;
    }
}
